package com.whfp.coky.ui.task.vm.fluor

import android.widget.EditText
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.whfp.coky.api.error.ErrorResult
import com.whfp.coky.databinding.ActivityFluorThresholdDetailBinding
import com.whfp.coky.db.DbFlowTools
import com.whfp.coky.db.dao.ProjectSettingDao
import com.whfp.coky.manager.InputTextManage
import com.whfp.coky.ui.base.BaseActivity
import com.whfp.coky.ui.base.BaseViewModel
import com.whfp.coky.ui.task.model.ThresholdInfoBean
import com.whfp.coky.utils.GsonUtils

/**
 *
 *
 * created by coky on 2022/3/1
 */
class ThresholdDetailVM : BaseViewModel<ActivityFluorThresholdDetailBinding>() {
    val COMMIT_OK = 200
    var result = MutableLiveData<String>()
    var tagId = MutableLiveData<Int>() //默认新增
    lateinit var ets: List<EditText>
    fun doActivation() {
//        跳转扫码
    }

    fun initIdBundle(id: Int?) {
        if (id == null) {
            tagId.value = -1
        } else {
            tagId.value = id
        }
    }

    override fun observe(activity: BaseActivity<*, *>, owner: LifecycleOwner) {
        super.observe(activity, owner)
        tagId.observe(activity, Observer {
            ets = listOf(
                vBinding.et01, vBinding.et02, vBinding.et03,
                vBinding.et11, vBinding.et12, vBinding.et13,
                vBinding.et21, vBinding.et22, vBinding.et23
            )
            buildEtListener(activity)
            if (it == -1) {
                activity.setTitle("新增阈值")
            } else {
                activity.setTitle("阈值详情")
                inputDatasByID(it)
            }
        })
    }

    //    监听新增数据(至少输入一条阈值)
    private fun buildEtListener(activity: BaseActivity<*, *>) {
        vBinding.btnSave.let {
            InputTextManage.with(activity).apply {
                for (index in 0..2) {
                    addView(ets[index])
                }
            }.setMain(it).build()
        }
    }

    //名称浓度信息
    private fun inputDatasByID(id: Int) {
        val bean: ProjectSettingDao = DbFlowTools.inquiryById(id)
        vBinding.etProjectName.let {
            it.setText(bean.projectName)
            it.isEnabled = false
        }
        vBinding.etDensityUnit.setText(bean.densityUnit)
        initThresholds(bean.thresholdInfo)
    }

    //    填充阈值信息
    private fun initThresholds(info: String?) {
        info?.let {
            var index = 0
            val datas = GsonUtils.jsonToArrayList(it, ThresholdInfoBean::class.java)
            for (num in datas.indices) {
                if (index > ets.size - 3) return@let
                ets[index++].setText(datas[num].lowerLimit.toString())
                ets[index++].setText(datas[num].upperLimit.toString())
                ets[index++].setText(datas[num].displayText)
            }
        }
    }

    //    检测项目名称和浓度单位
    fun checkInput(){
        var errMsg = ""
        val isFilled = vBinding.etProjectName.text.toString().isNotEmpty() &&
                vBinding.etDensityUnit.text.toString().isNotEmpty()
        if (isFilled) {
            var valueOk = true
            for (index in ets.indices step 3) {
                if (ets[index].getText().toString().toDouble()<=ets[index].getText().toString().toDouble()){
                    continue
                }else{
                    errMsg = "阈值范围设置错误.."
                    valueOk = false
                    break
                }
            }

            if (valueOk){
                if (tagId.value == -1) {//新建项目
                    val projBean = DbFlowTools.inquiryToName(vBinding.etProjectName.getText().toString())
                    if (projBean == null) {
                        doProjNew()
                    }else{//查询到同名项目
                        errMsg = "已存在同名设置,不可重复提交.."
                    }
                } else {//修改项目
                    doProjSave()
                }
            }
        } else {
            errMsg = "项目名称或浓度单位不可为空.."
        }
        if (errMsg.isNotEmpty()){
            errorData.value = ErrorResult(errMsg = errMsg, show = true)
        }
    }

    private fun doProjSave() {
//        保存
        if (DbFlowTools.updateProjectSetingById(tagId.value!!,buildCommitInfos())){
            errorData.value = ErrorResult(code = COMMIT_OK,errMsg = "修改成功", show = true)
        }else{
            errorData.value = ErrorResult(errMsg = "修改失败..", show = true)
        }
    }

    private fun doProjNew() {
//        新增
        if (buildCommitInfos().save()){
            errorData.value = ErrorResult(code = COMMIT_OK,errMsg = "添加成功", show = true)
        }else{
            errorData.value = ErrorResult(errMsg = "添加失败..", show = true)
        }
    }


    //
    fun buildCommitInfos():ProjectSettingDao {

        var beans = mutableListOf<ThresholdInfoBean>()
        for (index in ets.indices step 3) {
            if (ets[index].getText().toString().isNotEmpty()) {
                beans.add(
                    ThresholdInfoBean(
                        ets[index + 2].getText().toString(),
                        ets[index].getText().toString().toDouble(),
                        ets[index + 1].getText().toString().toDouble()
                    )
                )
            }
        }
        return ProjectSettingDao().apply {
            projectName = vBinding.etProjectName.getText().toString()
            densityUnit = vBinding.etDensityUnit.getText().toString()
            thresholdInfo = Gson().toJson(beans)
        }
    }


}